package ${basepackage}.controller.op;

import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import com.excalibur.shiro.shiro.util.ShiroUtils;
import com.excalibur.core.util.SpringUtils;
import com.excalibur.core.util.StringHelper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import ${basepackage}.controller.basic.DateTimeBinderController;
import ${basepackage}.manager.op.OpUserManager;
import ${basepackage}.manager.exception.ServiceException;
import ${basepackage}.model.json.JsonResponse;
import ${basepackage}.model.po.op.OpUser;
import ${basepackage}.model.vo.op.opuser.OpUserRow;
import ${basepackage}.model.vo.op.opuser.UpdateAccountForm;
import ${basepackage}.model.vo.op.opuser.UpdatePasswordForm;

@Controller
@RequestMapping(value = "/opUserAccount")
public class OpUserAccountController extends DateTimeBinderController {

	protected static final String UPDATE_ACCOUNT_CAPTCHA_KEY = "UpdateAccountCaptcha";
	protected static final String UPDATE_PASSWORD_CAPTCHA_KEY = "UpdatePasswordCaptcha";

	private final static Logger logger = LoggerFactory
			.getLogger(OpUserAccountController.class);

	@Autowired
	private OpUserManager opUserManager;

	/**
	 * 账号信息页面.
	 * 
	 * @return
	 */
	@RequestMapping(value = { "/account" })
	public String accountPage(ModelMap model) {
		OpUserRow user = new OpUserRow();
		try {
			user = opUserManager.getWithRolesByUsername(ShiroUtils
					.getPrincipal());
		} catch (ServiceException e) {
			logger.error("Failed to get account info！", e);
			model.put("msg", e.getMessage());
		}
		model.put("user", user);

		return "user/account";
	}

	/**
	 * 修改账号信息.
	 * 
	 * @param updateAccountForm
	 * @param validResult
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = { "/account/update" })
	@ResponseBody
	public JsonResponse updateAccount(
			@Valid UpdateAccountForm updateAccountForm,
			BindingResult validResult, HttpSession session) {
		JsonResponse jsonResponse = new JsonResponse();
		boolean result = false;
		// 验证结果检查
		if (validResult.hasErrors()) {
			if (validResult.hasFieldErrors("email")) {
				jsonResponse.setMessage(validResult.getFieldError("email")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("realName")) {
				jsonResponse.setMessage(validResult.getFieldError("realName")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("tel")) {
				jsonResponse.setMessage(validResult.getFieldError("tel")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("captcha")) {
				jsonResponse.setMessage(validResult.getFieldError("captcha")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("captchaKey")) {
				jsonResponse.setMessage(validResult.getFieldError("captchaKey")
						.getDefaultMessage());
			}
		} else {

			Map<String, String> captchaMap = (Map<String, String>) session
					.getAttribute(UPDATE_ACCOUNT_CAPTCHA_KEY);
			if (captchaMap != null) {

				String captchaText = captchaMap.get(updateAccountForm
						.getCaptchaKey());
				if (StringHelper.isNotBlank(captchaText)
						&& captchaText.equalsIgnoreCase(updateAccountForm
								.getCaptcha())) {
					try {
						OpUser opUser = opUserManager
								.updateAccount(updateAccountForm);
						jsonResponse.setCode(0);
						jsonResponse.setData(opUser);
						result = true;
					} catch (ServiceException e) {
						logger.error("Failed to update account！", e);
						jsonResponse.setMessage(e.getMessage());
					} catch (DataAccessException e) {
						logger.error("Failed to update account！", e);
						jsonResponse
								.setMessage(SpringUtils
										.getI18nMessage("webapp.controller.sysError"));
					}
				} else {
					jsonResponse
							.setMessage(SpringUtils
									.getI18nMessage("webapp.controller.captchaError"));
				}
			} else {
				jsonResponse
						.setMessage(SpringUtils
								.getI18nMessage("webapp.controller.captchaError"));
			}
		}

		if (!result) {
			jsonResponse.setCode(1);
		}

		return jsonResponse;
	}

	/**
	 * 账号密码页面.
	 * 
	 * @return
	 */
	@RequestMapping(value = { "/password" })
	public String passwordPage(ModelMap model) {
		return "user/password";
	}

	/**
	 * 修改账号密码.
	 * 
	 * @param updateAccountForm
	 * @param validResult
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = { "/password/update" })
	@ResponseBody
	public JsonResponse updatePassword(
			@Valid UpdatePasswordForm updatePasswordForm,
			BindingResult validResult, HttpSession session) {
		JsonResponse jsonResponse = new JsonResponse();
		boolean result = false;
		// 验证结果检查
		if (validResult.hasErrors()) {
			if (validResult.hasFieldErrors("password")) {
				jsonResponse.setMessage(validResult.getFieldError("password")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("newPassword")) {
				jsonResponse.setMessage(validResult
						.getFieldError("newPassword").getDefaultMessage());
			} else if (validResult.hasFieldErrors("rePassword")) {
				jsonResponse.setMessage(validResult.getFieldError("rePassword")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("captcha")) {
				jsonResponse.setMessage(validResult.getFieldError("captcha")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("captchaKey")) {
				jsonResponse.setMessage(validResult.getFieldError("captchaKey")
						.getDefaultMessage());
			}
		} else {
			Map<String, String> captchaMap = (Map<String, String>) session
					.getAttribute(UPDATE_PASSWORD_CAPTCHA_KEY);
			if (captchaMap != null) {

				String captchaText = captchaMap.get(updatePasswordForm
						.getCaptchaKey());
				if (StringHelper.isNotBlank(captchaText)
						&& captchaText.equalsIgnoreCase(updatePasswordForm
								.getCaptcha())) {
					try {
						result = opUserManager
								.updatePassword(updatePasswordForm);
						jsonResponse.setCode(0);
					} catch (ServiceException e) {
						logger.error("Failed to update password！", e);
						jsonResponse.setMessage(e.getMessage());
					} catch (DataAccessException e) {
						logger.error("Failed to update password！", e);
						jsonResponse
								.setMessage(SpringUtils
										.getI18nMessage("webapp.controller.sysError"));
					}
				} else {
					jsonResponse
							.setMessage(SpringUtils
									.getI18nMessage("webapp.controller.captchaError"));
				}
			} else {
				jsonResponse
						.setMessage(SpringUtils
								.getI18nMessage("webapp.controller.captchaError"));
			}
		}

		if (!result) {
			jsonResponse.setCode(1);
		}

		return jsonResponse;
	}

}
